import axios from 'axios'


const service = axios.create({
    responseType:'arraybuffer'
})


//响应拦截器  resp拿到返回的结果就是一个文件流
service.interceptors.response.use(resp=>{
    const headers = resp.headers;
    //定义正则表达式，接收流，下载文件这些特殊的流才会返回字符串，后端发送的数据大部分都是json数据
    let reg = RegExp(/application\/json/);
    if(headers['content-type'].match(reg)){
        resp.data= unitToString(resp.data);
    }else{
        let fileDowload = require('js-file-download');
        let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1];
        let contentType = headers['content-type'];
        //文件格式转化
        fileName=decodeURIComponent(fileName);
        //通过js-file-download下载我们的插件
        fileDowload(resp.data,fileName,contentType);
    }
},error=>{
    console.log(error);
});


function unitToString(unitArray){
    let encodeString = String.fromCharCode.apply(null,new Uint8Array(unitArray));
    let decodedString=decodeURIComponent(escape(encodeString));
    return JSON.parse(decodedString);
}


let base = '';
export const downloadRequest=(url,params)=>{
    return service({
        method: 'get',
        url:`${base}${url}`,
        data: params
    })
};

